<!--
 * @Descripttion: 
 * @version: 
 * @Author: ybac
 * @Date: 2022-10-31 17:46:47
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-06-25 11:07:36
-->
<template>
  <div class="home-wrap">
    <div>
      <a-card :bordered="false" style="height: calc(100vh - 205px)">
        <a-button @click="showColumn" icon="unordered-list" class="btns">设置列</a-button>
        <div class="right-btn">
          <a-button
            type="primary"
            style="margin-right: 10px"
            :loading="syncLoading"
            @click="synchronization"
            v-if="platform == '5'"
            >同步钉钉组织信息</a-button
          >
          <a-button style="margin-right: 10px" @click="handleExpandAll">全部展开</a-button>
          <a-button style="margin-right: 10px" @click="handleUnExpandAll">全部折叠</a-button>
          <a-button type="primary" @click="onClickAdd" v-if="platform != '5'">
            +新建
          </a-button>
        </div>
        <a-table
          row-key="id"
          :key="tableKey"
          :scroll="{ x: scrollX, y: 'calc(100vh - 345px)' }"
          :hideDefaultSelections="false"
          :columns="columns"
          :dataSource="tableData"
          :pagination="false"
          @change="tableChange"
          @expand="onExpand"
          :row-selection="rowSelection"
          :components="drag(columns, 'ORGANIZATION')"
          :expanded-row-keys.sync="expandedRowKeys"
          :defaultExpandAllRows="expandAll"
          :customRow="customRow"
          :loading="loadingTable"
          class="jek-table"
        >
          <div slot="actions" slot-scope="text, record" v-if="record.orgType != '1'">
            <a-button type="link" @click="onClickEdit(record)" v-if="platform != '5'">编辑</a-button>
            <!-- <a-popconfirm placement="top" ok-text="确认" cancel-text="取消" @confirm="onClickDelete(record.id)">
              <template slot="title">
                <span>确定删除吗？</span>
              </template>
            </a-popconfirm> -->
            <span class="btn-text" @click="onClickDelete(record.id)" v-if="platform != '5'">删除</span>
          </div>
          <div slot="actions" v-else></div>
          <div
            slot="userTotal"
            slot-scope="text, record"
            class="btn-text"
            :title="text || '-'"
            @click="onClickDetail(record)"
          >
            {{ text || '-' }}
          </div>
          <div slot="updateTime" slot-scope="text, record" :title="text || record.createTime">
            {{ text || record.createTime }}
          </div>
          <div
            slot="sort"
            style="cursor: pointer"
            slot-scope="text, record"
            title="拖拽排序"
            v-if="record.orgType != '1'"
          >
            <a-icon type="menu" />
          </div>
          <div slot="sort" v-else></div>
        </a-table>
        <SetColumn
          columnName="设置列"
          ref="SetColumn"
          v-if="showSetColumn"
          @sureBtn="sureBtn"
          @cancelBtn="showSetColumn = false"
        />
      </a-card>
    </div>
    <search-modal ref="searchModal" @handleFilter="handleFilter"></search-modal>
    <div
      class="uni-card resetPadding"
      :style="{
        position: 'fixed',
        bottom: 0,
        right: 0,
        zIndex: 2,
        left: collapsed ? '79px' : '208px',
        background: '#fff',
        paddingLeft: '43px',
      }"
    >
      <div style="display: inline-block" v-if="platform == '5'">
        <span style="margin-left: 8px"> 共{{ pagination.total }}条 </span>
      </div>
      <div style="display: inline-block" v-else>
        <a-checkbox :indeterminate="listIndeterminate" :checked="listCheckAll" @change="onCheckAllChange"></a-checkbox>
        <span style="margin-left: 8px">
          <span class="pubColor" style="margin: 0 18px" @click="onClickDelete()">删除</span>
          {{ `已选 ${selectedRowKeys.length}/${pagination.total} 项` }}
        </span>
        <span class="pubColor" @click="clearArr" style="margin: 0 10px">清空</span>
      </div>
      <div style="display: inline-block; float: right">
        <a-pagination
          :total="pagination.parentTotal"
          v-model="pagination.current"
          :page-size-options="pagination.options"
          :page-size="pagination.pageSize"
          @change="onChangePage"
          @showSizeChange="onChangePage"
          show-quick-jumper
          show-size-changer
        />
      </div>
    </div>
    <form-page ref="formPage" @success="requestData" :tenantId="tenantId"></form-page>
  </div>
</template>

<script>
import { getNewColumns } from '@/utils/util'
import SetColumn from '@/pubComponent/SetColumn.vue'
import tableDragResize from '@/mixins/tableDragResize'
import formPage from './form.vue'
import searchModal from './searchModal.vue'
import { columnsValue } from './column'
import { mapState } from 'vuex'
import { getAction, deleteAction, postAction } from '@/api/manage'
let companyId = ''
const actionArr = [
  {
    fixed: 'right',
    title: '操作',
    width: 120,
    dataIndex: 'actions',
    ellipsis: true,
    scopedSlots: { customRender: 'actions' },
  },
]
export default {
  name: 'ORGANIZATION',
  mixins: [tableDragResize],
  components: {
    SetColumn,
    formPage,
    searchModal,
  },
  data() {
    return {
      tableKey: 1.6,
      columnsValue,
      columns: JSON.parse(JSON.stringify(columnsValue)),
      tableData: [],
      pagination: {
        current: 1,
        pageSize: 10,
        options: ['10', '20', '30', '40', '50'],
        total: 0,
      },
      filterForm: {},
      showSetColumn: false,
      selectedRowKeys: [],
      listCheckAll: false,
      listIndeterminate: false,
      expandedRowKeys: [],
      expandAll: false,
      sourceVal: null,
      targetVal: null,
      sourceIndex: null,
      targetIndex: null,
      tenantId: null,
      loadingTable: false,
      platform: null,
      syncLoading: false,
    }
  },
  created() {
    var oldValue = localStorage.getItem(this.BUSI_CONST.Entity.ORGANIZATION)
    this.columns = getNewColumns(this.columnsValue, JSON.parse(oldValue), actionArr, this.columns)
    this.loadingTable = true
    this.tenantId = this.$store.getters.userInfo.tenantId
    this.requestData()
    getAction('/mgtTenantInfo/getTenantInfo').then((res) => {
      if (res.code == 200) {
        this.platform = res.result.type
      }
    })
  },
  computed: {
    ...mapState({
      collapsed: (state) => state.user.collapsed,
    }),
    scrollX() {
      let xnum = 0
      for (let item of this.columns) {
        xnum += Number(item.width) || 0
      }
      return xnum
    },
    filteredNums() {
      let nums = 0
      for (let key in this.filterForm) {
        if (this.filterForm[key]) {
          nums += 1
        }
      }
      return nums
    },
    rowSelection() {
      if (this.platform == '5') {
        return null
      }
      return {
        // { selectedRowKeys: selectedRowKeys, onChange: onSelectChange, fixed: true }
        onChange: (selectedRowKeys, selectedRows) => {
          this.onSelectChange(selectedRowKeys, selectedRows)
        },
        selectedRowKeys: this.selectedRowKeys,
        fixed: true,
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.id === companyId,
          },
        }),
      }
    },
  },
  methods: {
    synchronization() {
      this.syncLoading = true
      getAction('/sys/thirdApp/sync/toLocal')
        .then((res) => {
          if (res.code == 200) {
            this.$antdMessage.success(res.message)
            this.pagination.current = 1
            this.requestData()
          } else {
            this.$antdMessage.error(res.message)
          }
        })
        .finally(() => {
          this.syncLoading = false
        })
    },
    onExpand(bool, row) {
      if (bool) {
        this.expandedRowKeys.push(row.id)
      } else {
        this.expandedRowKeys = this.expandedRowKeys.filter((item) => item != row.id)
      }
    },
    onClickDetail(v) {
      if (v.userTotal) {
        this.$router.push({
          path: '/authManagement/userManagement',
          query: { departId: v.id },
        })
      }
    },
    customRow(record, index) {
      return {
        // FIXME: draggable： true 不生效还不晓得是什么原因，先使用鼠标移入事件设置目标行的draggable属性
        props: {
          draggable: 'true',
        },
        on: {
          // 鼠标移入
          mouseenter: (event) => {
            // 兼容IE
            var ev = event || window.event
            ev.target.draggable = true
          }, // 开始拖拽
          dragstart: (event) => {
            // 兼容IE
            var ev = event || window.event // 阻止冒泡
            ev.stopPropagation() // 得到源目标数据
            this.sourceVal = record
            this.sourceIndex = index
          }, // 拖动元素经过的元素
          dragover: (event) => {
            // 兼容 IE
            var ev = event || window.event // 阻止默认行为
            ev.preventDefault()
          }, // 鼠标松开
          drop: (event) => {
            // 兼容IE
            var ev = event || window.event // 阻止冒泡
            ev.stopPropagation() // 得到目标数据
            if (record.orgType == '1') {
              this.$antdMessage.warning('只能对同一个层级之间的上下顺序进行排序')
              return
            }
            this.targetVal = record
            this.targetIndex = index
            if (this.sourceVal.id !== this.targetVal.id) {
              if (this.sourceVal.parentId === this.targetVal.parentId) {
                this.resetTableSort(this.sourceVal, this.targetVal, this.sourceIndex, this.targetIndex)
              } else {
                this.$antdMessage.warning('只能对同一个层级之间的上下顺序进行排序')
              }
            }
          },
        },
      }
    },
    // 拖拽结束后根据源目标数据、目标数据重组列表
    resetTableSort(sourceVal, targetVal, sourceIndex, targetIndex) {
      console.log(sourceVal.departName, targetVal.departName, sourceIndex, targetIndex)
      let treeFun = (arr) => {
        for (let i = 0; i < arr.length; i++) {
          const item = arr[i]
          if (item.id == sourceVal.id) {
            arr[sourceIndex] = targetVal
            arr[targetIndex] = sourceVal
            this.sorterFun(arr)
            return
          }
          if (item.children && item.children.length > 0) {
            treeFun(item.children)
          }
        }
      }
      treeFun(this.tableData)
    },
    sorterFun(arr) {
      for (let i = 0; i < arr.length; i++) {
        arr[i].departOrder = i
      }
      this.loadingTable = true
      // sysDepartQueryEditLocation(arr)
      postAction('/sys/sysDepart/editLocation', arr)
        .then((res) => {
          if (res.code == 200) {
            this.$antdMessage.success(res.message)
          } else {
            this.$antdMessage.success(res.message)
          }
          this.requestData()
        })
        .catch((err) => {
          this.loadingTable = false
        })
    },
    // 全部展开
    handleExpandAll() {
      this.expandAll = true
      this.tableKey += 1
    },
    // 全部折叠
    handleUnExpandAll() {
      this.expandedRowKeys = []
    },
    // 增
    onClickAdd() {
      let pid = ''
      if (this.tableData.length > 0) {
        pid = this.tableData[0].id
      }
      this.$refs.formPage.open(pid)
    },
    // 删
    onClickDelete(id) {
      let that = this
      if (id) {
        //单个删除
        // deleteAction('/sys/sysDepart/delete', { id }).then((res) => {
        //   if (res.code == 200) {
        //     this.$antdMessage.success('删除成功！')
        //     this.clearArr()
        //     if (this.tableData.length === 1) {
        //       this.pagination.current = this.pagination.current == 1 ? 1 : this.pagination.current - 1
        //     }
        //     this.requestData()
        //   } else {
        //     this.$antdMessage.error(res.message)
        //   }
        // })
        that.$antdConfirm({
          title: '确定删除部门吗？',
          content: `部门人数为零才可以进行删除，删除后下级部门也会同步删除！`,
          onOk() {
            deleteAction('/sys/sysDepart/delete', { id }).then((res) => {
              if (res.code == 200) {
                that.clearArr()
                that.pagination.current = 1
                that.requestData()
                that.$antdMessage.success('删除成功！')
              } else {
                that.$antdMessage.error(res.message)
              }
            })
          },
          onCancel() {},
        })
      } else {
        //批量删除
        if (that.selectedRowKeys.length == 0) {
          this.$antdMessage.info('请选择数据！')
          return
        }
        that.$antdConfirm({
          title: '请确定要删除吗?',
          content: `共选中${that.selectedRowKeys.length}条信息`,
          onOk() {
            deleteAction('/sys/sysDepart/deleteBatch', { ids: that.selectedRowKeys.join(',') }).then((res) => {
              if (res.code == 200) {
                that.clearArr()
                that.pagination.current = 1
                that.requestData()
                that.$antdMessage.success('删除成功！')
              } else {
                that.$antdMessage.error(res.message)
              }
            })
          },
          onCancel() {},
        })
      }
    },
    // 改
    onClickEdit(record) {
      this.$refs.formPage.editor({ ...record, tenantId: this.tenantId })
    },
    // 查
    requestData() {
      this.loadingTable = true
      let params = {
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        tenantId: this.tenantId,
        ...this.filterForm,
      }
      getAction('/sys/sysDepart/getList', params)
        .then((res) => {
          if (res.code == 200) {
            this.tableData = res.result.list
            this.pagination.total =
              Number(res.result.total) > 0 ? Number(res.result.total) - 1 : Number(res.result.total)
            this.pagination.parentTotal = Number(res.result.parentTotal)
            if (this.tableData.length > 0) {
              companyId = this.tableData[0].id
            }
            this.checkBoxStatus()
          } else {
            this.$antdMessage.error(res.message)
          }
          this.loadingTable = false
        })
        .catch((err) => {
          this.loadingTable = false
        })
    },
    // 排序
    tableChange(pagination, filters, sorter, { currentDataSource }) {
      this.current = 1
      if (sorter.order) {
        let sortType = ''
        if (sorter.order == 'ascend') {
          sortType = 'ASC'
        } else {
          sortType = 'DESC'
        }
        this.sortForm = {
          sortType: sortType,
          sortColumn: sorter.columnKey,
        }
        this.requestData()
      } else {
        this.sortForm = {
          sortType: '',
          sortColumn: '',
        }
        this.requestData()
      }
    },
    // 筛选
    handleShowFilter() {
      this.$refs.searchModal.openFilter(this.filterForm)
    },
    handleFilter(form) {
      console.log('form是怎样：', form)
      this.pagination.current = 1
      this.filterForm = JSON.parse(JSON.stringify(form))
      this.requestData()
    },
    // 分页
    onChangePage(current, pageSize) {
      this.pagination.current = current
      this.pagination.pageSize = pageSize
      this.requestData()
    },
    /* 打开设置列面板 */
    showColumn() {
      this.showSetColumn = true
      this.$nextTick(() => {
        this.$refs.SetColumn.paramsData(this.columnsValue, this.BUSI_CONST.Entity.ORGANIZATION, this.columns)
      })
    },
    /* 设置列 */
    sureBtn(emitArr) {
      localStorage.setItem(this.BUSI_CONST.Entity.ORGANIZATION, JSON.stringify(emitArr))
      this.columns = getNewColumns(this.columnsValue, emitArr, actionArr)
      this.tableKey += 1
    },
    // table选择
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.checkBoxStatus()
    },
    // 底部全选
    onCheckAllChange(e) {
      let tableList = []
      let tree = (arr) => {
        for (let i = 0; i < arr.length; i++) {
          const item = arr[i]
          if (item.orgType != '1') {
            tableList.push(item)
          }
          if (item.children && item.children.length > 0) {
            tree(item.children)
          }
        }
      }
      tree(this.tableData)
      if (e.target.checked) {
        for (let item of tableList) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
          this.selectedRowKeys.push(item.id)
        }
      } else {
        for (let item of tableList) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
        }
      }
      this.checkBoxStatus()
    },
    // 底部清空
    clearArr() {
      this.selectedRowKeys = []
      this.checkBoxStatus()
    },
    checkBoxStatus() {
      let tableList = []
      let tree = (arr) => {
        for (let i = 0; i < arr.length; i++) {
          const item = arr[i]
          if (item.orgType != '1') {
            tableList.push(item)
          }
          // tableList.push(item)
          if (item.children && item.children.length > 0) {
            tree(item.children)
          }
        }
      }
      tree(this.tableData)
      if (this.selectedRowKeys.length == 0) {
        this.listIndeterminate = false
        this.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of tableList) {
          tableIds.push(item.id)
        }
        let checkValue = this.isInclude(tableIds, this.selectedRowKeys)
        if (checkValue) {
          this.listIndeterminate = false
          this.listCheckAll = true
        } else {
          this.listIndeterminate = true
          this.listCheckAll = false
        }
      }
    },
    isInclude(aa, bb) {
      return aa.every((item) => {
        return bb.some((sub) => {
          return sub === item
        })
      })
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@/assets/less/public.less';
.pubColor {
  font-size: 14px;
  color: #1890ff;
  cursor: pointer;
}
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
.flex-box {
  display: flex;
  // justify-content: space-between;
  align-items: center;
}
.searchWorkOreder {
  .flex(flex-start, center);
  padding: 8px;
}
.btns {
  margin-left: 10px;
}
.right-btn {
  float: right;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}
</style>
